import { Action, PermissionsTo, fromParam, JwtPayload, JwtPayloadDto, fromBody } from '@boticord/auth'
import { ErrorCodes } from '@boticord/consts'
import { ChangeReportStatusDto, CreateReportDto, Report } from '@boticord/resources-client'
import { User } from '@boticord/users-client'
import { Body, Controller, Get, NotFoundException, Param, Post, Put } from '@nestjs/common'
import { InjectRepository } from '@nestjs/typeorm'
import { Repository } from 'typeorm'
import { ReportsService } from '../services/reports.service'
import { AnalyseRequest, EventTypes } from '@boticord/analytics'

@Controller('reports')
export class ReportController {
  constructor(
    private readonly reports: ReportsService,
    @InjectRepository(User) private readonly users: Repository<User>,
  ) {}

  @Get()
  @PermissionsTo(Action.ReadMany, Report)
  async getReports() {
    return this.reports.getAll()
  }

  @Get(':id')
  @PermissionsTo(Action.Read, Report, { fetch: { id: fromParam('id') } })
  async getReport(@Param('id') id: string) {
    return this.reports.get(id)
  }

  @Post()
  @PermissionsTo(Action.Create, Report)
  @AnalyseRequest(EventTypes.ReportAdded, {
    affected: fromBody('resourceID'),
  })
  async createReport(@Body() dto: CreateReportDto, @JwtPayload() payload: JwtPayloadDto) {
    const user = await this.users.findOne({ where: { id: payload.id } })
    
    if (user === null) {
      throw new NotFoundException({ code: ErrorCodes.UnknownUser })
    }

    return await this.reports.create(user, dto) 
  }

  @Put('status/:id')
  @PermissionsTo(Action.ChangeStatus, Report)
  async changeStatus(@Param('id') reportID: string, @Body() dto: ChangeReportStatusDto) {
    return await this.reports.changeStatus(reportID, dto.to)
  }
}
